package com.wj.wjpicture.application.service.impl;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wj.wjpicture.application.service.PictureApplicationService;
import com.wj.wjpicture.domain.picture.service.PictureDomainService;
import com.wj.wjpicture.infrastructure.api.aliyun.model.CreateOutPaintingTaskResponse;
import com.wj.wjpicture.infrastructure.exception.BusinessException;
import com.wj.wjpicture.infrastructure.exception.ErrorCode;
import com.wj.wjpicture.interfaces.dto.picture.*;
import com.wj.wjpicture.domain.picture.entity.Picture;
import com.wj.wjpicture.domain.user.entity.User;
import com.wj.wjpicture.interfaces.vo.picture.PictureVO;
import com.wj.wjpicture.infrastructure.mapper.PictureMapper;
import com.wj.wjpicture.application.service.UserApplicaitonService;
import com.wj.wjpicture.interfaces.vo.user.UserVO;
import lombok.extern.slf4j.Slf4j;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 20231001
* @description 针对表【PictureUploadRequest(图片)】的数据库操作Service实现
* @createDate 2025-07-14 09:40:31
*/
@Service
@Slf4j
public class PictureApplicationServiceImpl extends ServiceImpl<PictureMapper, Picture>
    implements PictureApplicationService {

//    @Resource
//    private FileManager fileManager;
    @Resource
    private UserApplicaitonService userApplicaitonService;
    @Resource
    private PictureDomainService pictureDomainService;

    @Override
    public PictureVO uploadPicture(Object inputSource, PictureUploadRequest pictureUploadRequest, User loginUser) {
        return pictureDomainService.uploadPicture(inputSource, pictureUploadRequest, loginUser);
    }

    // 删除图片
    @Override
    public void deletePicture(long pictureId, User loginUser) {
        pictureDomainService.deletePicture(pictureId, loginUser);
    }



    // 将查询请求转化为QueryWrapper对象
    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        return pictureDomainService.getQueryWrapper(pictureQueryRequest);
    }

    // 编辑图片
    @Override
    public void editPicture(Picture picture, User loginUser) {
        pictureDomainService.editPicture(picture, loginUser);
    }


    // 获取图片封装
    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {
        // 对象转封装类
        PictureVO pictureVO = PictureVO.objToVo(picture);
        // 关联查询用户信息
        Long userId = picture.getUserId();
        if (userId != null && userId > 0) {
            User user = userApplicaitonService.getUserById(userId);
            UserVO userVO = userApplicaitonService.getUserVO(user);
            pictureVO.setUser(userVO);
        }
        return pictureVO;
    }

    // 分页获取图片封装
    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage, HttpServletRequest request) {
        List<Picture> pictureList = picturePage.getRecords();
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(),picturePage.getTotal());
        if(CollUtil.isEmpty(pictureList)){
            return pictureVOPage;
        }
        // 对象列表 => 封装对象列表
        List<PictureVO> pictureVOList = pictureList.stream().map(PictureVO::objToVo).collect(Collectors.toList());
        // 1.关联用户信息
        List<Long> userIdSet = pictureList.stream().map(Picture::getUserId).collect(Collectors.toList());
        // 通过用户id查询用户并根据id进行分类   userID为key，User为value
        Map<Long, List<User>> userIdUserListMap = userApplicaitonService.listByIds(userIdSet).stream().collect(Collectors.groupingBy(User::getId));
        // 2.填充信息(给一个pictureVO对象关联userVO)
        pictureVOList.forEach(pictureVO -> {
            Long userId = pictureVO.getUserId();
            User user = null;
            if(userIdUserListMap.containsKey(userId)){
                user = userIdUserListMap.get(userId).get(0);
            }
            pictureVO.setUser(userApplicaitonService.getUserVO(user));
        });
        pictureVOPage.setRecords(pictureVOList);
        return pictureVOPage;
        /*
        注意，这里我们做了个小优化，不是针对每条数据都查询一次用户，
        而是先获取到要查询的用户 id 列表，只发送一次查询用户表的请求，再将查到的值设置到图片对象中。  这样减小了数据库查询的操作
     */
    }

    // 图片审核
    @Override
    public void doPictureReview(PictureReviewRequest pictureReviewRequest, User loginUser) {
        pictureDomainService.doPictureReview(pictureReviewRequest, loginUser);
    }

    // 设置审核状态
    @Override
    public void fillReviewParams(Picture picture, User loginUser) {
        pictureDomainService.fillReviewParams(picture, loginUser);
    }

    // 批量抓取和创建图片
    @Override
    public Integer uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, User loginUser) {
       return pictureDomainService.uploadPictureByBatch(pictureUploadByBatchRequest, loginUser);
    }

    // 清理图片
    @Async
    @Override
    public void clearPictureFile(Picture oldPicture) {
        pictureDomainService.clearPictureFile(oldPicture);
    }

    // 权限校验
    @Override
    public void checkPictureAuth(User loginUser, Picture picture) {
       pictureDomainService.checkPictureAuth(loginUser, picture);
    }

    /**
     * 按颜色查询图片
     * @param spaceId
     * @param picColor
     * @param loginUser
     * @return
     */
    @Override
    public List<PictureVO> searchPictureByColor(Long spaceId, String picColor, User loginUser) {
        return pictureDomainService.searchPictureByColor(spaceId, picColor, loginUser);
    }


    // 创建扩图任务
    @Override
    public CreateOutPaintingTaskResponse createPictureOutPaintingTask(CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest
                                                                        , User loginUser)
    {
        return pictureDomainService.createPictureOutPaintingTask(createPictureOutPaintingTaskRequest, loginUser);
    }

    public void validPicture(Picture picture){
        if (picture == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        picture.validPicture();
    }

    /**
     * 批量编辑图片分类和标签
     */
    @Override
    public void editPictureByBatch(PictureEditByBatchRequest pictureEditByBatchRequest, User loginUser) {
        pictureDomainService.editPictureByBatch(pictureEditByBatchRequest, loginUser);
    }


}




